<?php
/*
 *
 * @package MoltX
 * @author $Author$
 * @version $Id$
 * @link $URL$
 * @copyright Copyright (c) 2005-2010, Matthew Oltendorf
 * @license http://opensource.org/licenses/gpl-license.php GNU Public License
 *
 */

/*
 * @ignore
 */
if ( ! defined ( 'blink' ) )
{
	// Access denied.
	header ( $_SERVER [ 'SERVER_PROTOCOL' ] . ' 403 Forbidden' );
	echo '403 - Forbidden';

	exit;
}

/*
 * Blink socket class
 * @package Blink
 *
 * Factory
 */
final class blink_socket
{
	private	$stream;

	/*
	 * Constructor function
	 *
	 * @param resource $stream the stream resource to use for all communications.
	 *
	 * @return null
	 */
	public function __construct ( $stream )
	{
		$this -> stream = $stream;

		return null;
	}

	/*
	 * Close message function
	 *
	 * Closes a connection to a client.
	 *
	 * @return string
	 */
	public function close ( )
	{
		try
		{
			fclose ( $this -> stream );
		}
		catch ( Exception $exception )
		{
			// Who will close it first? We may never know.
		}

		return null;
	}

	/*
	 * Get message function
	 *
	 * Gets a message received from a client.
	 *
	 * @return string
	 */
	public function get ( )
	{
		try
		{
			list ( $length ) = array_values ( unpack ( 'N', stream_get_contents ( $this -> stream, 4 ) ) );
			$message = unserialize ( stream_get_contents ( $this -> stream, $length ) );

			return $message;
		}
		catch ( Exception $exception )
		{
			// Development only. @todo: Remove for production.
			blink_console :: log ( 'got bad data' );

			return null;
		}
	}

	/*
	 * Send message function
	 *
	 * Sends a message sent to a client.
	 *
	 * @param string $message the message to send.
	 *
	 * @return boolean
	 */
	public function send ( $message )
	{
		$message = serialize ( $message );
		$length = pack ( 'N', strlen ( $message ) );

		$data = $length . $message;
		$length = strlen ( $data );

		if ( fwrite ( $this -> stream, $data ) < $length )
		{
			throw new Exception ( 'SEND DATA FAILED' );
		}

		return true;
	}
}
